﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml.Linq;
using CKS.Sandbox.TipOfTheDayProxy;
using Microsoft.SharePoint.Utilities;
using System.Text.RegularExpressions;
namespace CKS.Sandbox.TipOfTheDay
{
    [ToolboxItemAttribute(false)]
    public class TipsViewer : WebPart
    {
        public TipsViewer()
        {
        }

        [Personalizable(PersonalizationScope.Shared),
         WebBrowsable(true),
         WebDisplayName("Is RSS a source for tip of the day?"),
         Category("CKS WebPart Property")]
        public Boolean IsRSS { get; set; } 
        
        [Personalizable(PersonalizationScope.Shared),
         WebBrowsable(true),
         WebDisplayName("The url of the RSS feed for tip of the day."),
         Category("CKS WebPart Property")]
         public Uri ListURL { get; set; }

        private string tipText;
        private string TipTemplateWithDesc = "<table width='35%'><tr> <td rowspan='2'> <img src='../../SiteAssets/TipOfTheDay/Idea.jpg'></td><td>{0}</td></tr><tr><td>{1}</td></tr></table>";
        private string TipTemplateWithoutDesc = "<table width='35%'><tr><td><img src='../../SiteAssets/TipOfTheDay/Idea.jpg'></td><td>{0}</td></tr></table>";

        protected override void CreateChildControls()
        {
            tipText = string.Empty;
            Label tip = new Label();
            this.Controls.Add(tip);
        
            Button nextTip = new Button();
            nextTip.Text = "Next Tip";
            this.Controls.Add(nextTip);
          
            nextTip.Click += delegate
            {
                setTipOfTheDay();
                tip.Text = tipText;
            };

            if (tipText.Equals(string.Empty))
            {
                tip.Text = getTipOfTheDay();
            }
            else
            {
                tip.Text = tipText;
            }
        }

        private void setTipOfTheDay()
        {
            ProxyArgs args = new ProxyArgs();
            args.RssFeed = ListURL;

            if (IsRSS)
            {
                if (ListURL != null && ListURL.ToString().Trim() != string.Empty)
                {

                    string rssfeed = SPUtility.ExecuteRegisteredProxyOperation(
                             "CKS.Sandbox.TipOfTheDayProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5e4f17d9b4a7f1f9",
                              "CKS.Sandbox.TipOfTheDayProxy.Proxy",
                              args).ToString();


                    string[] splits = Regex.Split(rssfeed, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                    tipText = string.Format(TipTemplateWithoutDesc, "<a href='" + splits[1].Replace("\"", string.Empty) + "'>" + splits[0].Replace("\"", string.Empty) + "</a>");
                }
            }
            else
            {
                SPWeb web = SPContext.Current.Site.RootWeb;
                SPList list = web.Lists["Tips"];
                if (list.ItemCount > 0)
                {
                    int i = (new Random().Next(0, list.ItemCount));
                    tipText = string.Format(TipTemplateWithDesc, "<b>" + list.Items[i]["Title"].ToString() + "</b>", list.Items[i]["Text"].ToString());
                }

            }

            if (!tipText.Equals(string.Empty))
            {
                SPWeb site = SPContext.Current.Site.RootWeb;
                SPList instance = site.Lists.TryGetList("TipStore");
                SPListItem item = instance.Items[0];
                item["Text"] = tipText;
                item["DateAdded"] = DateTime.Now;
                item.Update();
                instance.Update();
            }

        }

        private string getTipOfTheDay()
        {
           SPWeb site = SPContext.Current.Site.RootWeb;
            SPList instance = site.Lists.TryGetList("TipStore");
            if (Convert.ToDateTime(instance.Items[0]["DateAdded"]) < DateTime.Now)
            {
                setTipOfTheDay();
            }
            return instance.Items[0]["Text"].ToString();
        }
    }
}
